package com.ruoyi.project.ins.service.impl;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.project.ins.domain.InsAccount;
import com.ruoyi.project.ins.service.IInsAccountService;
import com.ruoyi.project.mapper.InsAccountMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Validator;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class InsAccountServiceImpl implements IInsAccountService {

    @Autowired
    private InsAccountMapper insAccountMapper;

    @Autowired
    protected Validator validator;

    @Override
    public List<InsAccount> selectAccountList(InsAccount insAccount) {
        return insAccountMapper.selectAccountList(insAccount);
    }

    @Override
    public String importAccount(List<InsAccount> insAccountList, String operateName) {
        if (CollectionUtils.isEmpty(insAccountList)) {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (InsAccount insAccount : insAccountList)
        {
            try
            {
                // 验证用户id是否已存在
                InsAccount ins = insAccountMapper.selectByUserId(insAccount.getUserId());
                if (ObjectUtils.isEmpty(ins)) {
                    BeanValidators.validateWithException(validator, insAccount);
                    insAccount.setStatus("0");
                    insAccount.setSourceType("1");
                    insAccount.setSendTimes(0);
                    insAccount.setCreateBy(operateName);
                    insAccountMapper.insertInsAccount(insAccount);
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、用户id ")
                            .append(insAccount.getUserId()).append(" 导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、用户id ")
                            .append(insAccount.getUserId()).append(" 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、用户id " + insAccount.getUserId() + " 导入失败：";
                failureMsg.append(msg).append(e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public int insertInsAccount(InsAccount insAccount) {
        return insAccountMapper.insertInsAccount(insAccount);
    }

    @Override
    public int updateInsAccount(InsAccount insAccount) {
        return insAccountMapper.updateInsAccount(insAccount);
    }

    @Override
    public InsAccount selectAccountById(Long id) {
        return insAccountMapper.selectAccountById(id);
    }

    @Override
    public int deleteByIds(Long[] deleteIds) {
        return insAccountMapper.deleteByIds(deleteIds);
    }

    @Override
    public InsAccount selectByUserId(String emailAccount) {
        return insAccountMapper.selectByUserId(emailAccount);
    }

    @Override
    public List<InsAccount> selectByIds(Long[] ids) {
        return insAccountMapper.selectByIds(ids);
    }

    @Override
    public List<InsAccount> selectNoNameUser() {
        return insAccountMapper.selectNoNameUser();
    }

    @Override
    public int updateAccountStatusById(Long id) {
        return insAccountMapper.updateAccountStatusById(id);
    }

    @Override
    public void batchUpdateInsAccount(List<InsAccount> insAccountList) {
        if (CollectionUtils.isEmpty(insAccountList)) {
            return;
        }
        int total = insAccountList.size();
        for (int i = 0; i < total; i += Constants.MYBATIS_BATCH_MAX_SIZE) {
            int end = Math.min(i + Constants.MYBATIS_BATCH_MAX_SIZE, total);
            List<InsAccount> subList = insAccountList.subList(i, end);
            insAccountMapper.batchUpdateInsAccount(subList);  // 调用MyBatis批量更新
        }
    }

    @Override
    public void batchUpdateSendTimes(List<InsAccount> accountList) {
        if (CollectionUtils.isEmpty(accountList)) {
            return;
        }
        int total = accountList.size();
        for (int i = 0; i < total; i += Constants.MYBATIS_BATCH_MAX_SIZE) {
            int end = Math.min(i + Constants.MYBATIS_BATCH_MAX_SIZE, total);
            List<InsAccount> subList = accountList.subList(i, end);
            insAccountMapper.batchUpdateSendTimes(subList);  // 调用MyBatis批量更新
        }
    }

    @Override
    public int updateSendTimesByUserId(String userId) {
        return insAccountMapper.updateSendTimesByUserId(userId);
    }

    @Override
    public void batchUpdateSuccessTimes(List<InsAccount> accountList) {
        if (CollectionUtils.isEmpty(accountList)) {
            return;
        }
        int total = accountList.size();
        for (int i = 0; i < total; i += Constants.MYBATIS_BATCH_MAX_SIZE) {
            int end = Math.min(i + Constants.MYBATIS_BATCH_MAX_SIZE, total);
            List<InsAccount> subList = accountList.subList(i, end);
            insAccountMapper.batchUpdateSuccessTimes(subList);  // 调用MyBatis批量更新
        }
    }

    @Override
    public List<InsAccount> selectNeedCheckAccount() {
        return insAccountMapper.selectNeedCheckAccount();
    }
}
